<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="SKU ID" prop="skuId">
        <el-input
          v-model="queryParams.skuId"
          placeholder="请输入SKU ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分" prop="rate">
        <el-input
          v-model="queryParams.rate"
          placeholder="请输入评分"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:review:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reviewList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="订单号" align="center" prop="orderNumber" /> -->
      <!-- <el-table-column label="用户id" align="center" prop="userId" /> -->
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="点赞次数" align="center" prop="likes" />
      <el-table-column label="内容" align="center" prop="description" />
      <el-table-column label="评分" align="center" prop="rate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"  width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleViewReplies(scope.row)" v-hasPermi="['system:review:edit']">查看回复</el-button>
          <el-button link type="primary" icon="ChatLineSquare" @click="handleReply(scope.row)" v-hasPermi="['system:review:edit']">回复</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:review:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看回复对话框 -->
    <el-dialog title="评价回复列表" v-model="replyData.dialogVisible" width="800px" append-to-body>
      <el-table :data="replyData.replies" v-loading="replyData.loading">
        <el-table-column label="回复ID" prop="id" width="80" />
        <el-table-column label="用户ID" prop="userId" width="80" />
        <el-table-column label="回复内容" prop="content" show-overflow-tooltip />
        <el-table-column label="回复时间" prop="createdTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" icon="ChatLineSquare" @click="handleReplyTo(scope.row)">回复</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyData.dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Review">
import { listReview } from "@/api/order/review";
import { replyReview, listReplies } from "@/api/order/replies";
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance();

const reviewList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderItemId: null,
    userId: null,
    nickName: null,
    spuId: null,
    skuId: null,
    title: null,
    likes: null,
    description: null,
    rate: null,
    deleteTime: null,
    isDelete: null
  },
  rules: {
  }
});

// 添加回复列表相关数据
const replyData = reactive({
  replies: [],
  loading: false,
  dialogVisible: false,
  currentReview: null
});

const { queryParams, form, rules } = toRefs(data);

/** 查询评价列表 */
function getList() {
  loading.value = true;
  listReview(queryParams.value).then(response => {
    reviewList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderItemId: null,
    userId: null,
    spuId: null,
    skuId: null,
    title: null,
    likes: null,
    description: null,
    rate: null,
    createTime: null,
    updateTime: null,
    deleteTime: null,
    createBy: null,
    updateBy: null,
    isDelete: null
  };
  proxy.resetForm("reviewRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除评价编号为"' + _ids + '"的数据项？').then(function() {
    return delReview(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/**
 * 查看回复按钮操作
 */
function handleViewReplies(row) {
  replyData.currentReview = row;
  getRepliesList(row.id);
  replyData.dialogVisible = true;
}

/**
 * 获取回复列表
 */
function getRepliesList(reviewId) {
  replyData.loading = true;
  listReplies(reviewId).then(response => {
    replyData.replies = response.rows;
    replyData.loading = false;
  }).catch(() => {
    replyData.loading = false;
  });
}

/**
 * 回复按钮操作
 */
function handleReply(row) {
  proxy.$prompt('请输入回复内容', '回复评价', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '回复内容不能为空'
  }).then(({ value }) => {
    // 获取当前登录用户ID - 使用更可靠的方式
    const userStore = useUserStore();
    
    // 先调用 getInfo 确保获取最新用户信息
    userStore.getInfo().then(res => {
      console.log('User info response:', res);
      const currentUserId = res.user?.userId || 100;
      console.log('当前登录用户ID：', currentUserId);
      
      const replyDataParams = {
        reviewId: row.id,
        userId: currentUserId, // 使用当前登录用户ID
        content: value,
        parentId: null,
        replyToUserId: null
      };
      replyReview(replyDataParams).then(response => {
        proxy.$modal.msgSuccess("回复成功");
        // 刷新回复列表
        if (replyData.dialogVisible && replyData.currentReview && replyData.currentReview.id === row.id) {
          getRepliesList(row.id);
        }
      }).catch(() => {});
    }).catch(() => {
      // 如果 getInfo 失败，使用默认值
      const currentUserId = 1;
      const replyDataParams = {
        reviewId: row.id,
        userId: currentUserId,
        content: value,
        parentId: null,
        replyToUserId: null
      };
      replyReview(replyDataParams).then(response => {
        proxy.$modal.msgSuccess("回复成功");
        // 刷新回复列表
        if (replyData.dialogVisible && replyData.currentReview && replyData.currentReview.id === row.id) {
          getRepliesList(row.id);
        }
      }).catch(() => {});
    });
  }).catch(() => {
    // 取消操作
  });
}

/**
 * 回复某条评论
 */
// function handleReplyTo(row) {
//   proxy.$prompt('请输入回复内容', '回复', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     inputPattern: /\S/,
//     inputErrorMessage: '回复内容不能为空'
//   }).then(({ value }) => {
//     // 获取当前登录用户ID - 使用更可靠的方式
//     const userStore = useUserStore();
//     
//     // 先调用 getInfo 确保获取最新用户信息
//     userStore.getInfo().then(res => {
//       console.log('User info response:', res);
//       const currentUserId = res.user?.userId || 1;
//       console.log('当前登录用户ID：', currentUserId);
//       
//       const replyDataParams = {
//         reviewId: row.reviewId,
//         userId: currentUserId, // 使用当前登录用户ID
//         content: value,
//         parentId: row.id, // 设置父回复ID
//         replyToUserId: row.userId // 设置被回复用户ID
//       };
//       replyReview(replyDataParams).then(response => {
//         proxy.$modal.msgSuccess("回复成功");
//         // 重新加载回复列表
//         getRepliesList(row.reviewId);
//       }).catch(() => {});
//     }).catch(() => {
//       // 如果 getInfo 失败，使用默认值
//       const currentUserId = 1;
//       const replyDataParams = {
//         reviewId: row.reviewId,
//         userId: currentUserId,
//         content: value,
//         parentId: row.id,
//         replyToUserId: row.userId
//       };
//       replyReview(replyDataParams).then(response => {
//         proxy.$modal.msgSuccess("回复成功");
//         // 重新加载回复列表
//         getRepliesList(row.reviewId);
//       }).catch(() => {});
//     });
//   }).catch(() => {
//     // 取消操作
//   });
// }


getList();
</script>